package com.server.llh.llhserverwork.activity.server;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.BaseFragment;
import com.server.llh.llhserverwork.adapter.SerOrderInfoHolder;
import com.server.llh.llhserverwork.bean.SerOrderInfo;
import com.server.llh.llhserverwork.port.RemoverPositionInterface;
import com.server.llh.llhserverwork.port.SerOrderInfoInterface;
import com.server.llh.llhserverwork.utils.ServerPort;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Created by ZTF on 2017-05-27.
 * 服务订单Fragmnet
 */
public class SerOrderFragment extends BaseFragment implements SerOrderInfoInterface,RemoverPositionInterface {
    private static final String FRAGMENT_INDEX = "fragment_index";
    private final int FIRST_FRAGMENT = 0;
    private final int SECOND_FRAGMENT = 1;
    private int mCurIndex = -1;
    Unbinder unbinder;
    @BindView(R.id.fragment_listview)
    ListView fragmentListview;
    SwipeRefreshLayout refrash_data;
    private String mUserId;
    private static final String TAG = "SerOrderFragment";
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    /**
     * 是否已被加载过一次，第二次就不再去请求数据了
     */
    private boolean mHasLoadedOnce;
    View rootView;
    RemoverPositionInterface removerPositionInterface=null;
    public static SerOrderFragment newInstance(int index, String   userId) {
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_INDEX, index);
        bundle.putString("userId", userId);
        SerOrderFragment fragment = new SerOrderFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            Bundle bundle = getArguments();
            if (bundle != null) {
                mCurIndex = bundle.getInt(FRAGMENT_INDEX);
                mUserId=bundle.getString("userId");
            }

            isPrepared = true;
            lazyLoad();
        }
        refrash_data= (SwipeRefreshLayout) rootView.findViewById(R.id.refrash_data);
        refrash_data.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                onRefreshReq();
            }
        });
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }
    private void onRefreshReq() {
        if (mHasLoadedOnce == false || isPrepared == false || mHasLoadedOnce) {
            mHasLoadedOnce = true;
            isPrepared = true;
            mHasLoadedOnce = false;
        }
        lazyLoad();
    }
    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void initView(View view) {
//        mUserId= SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID,this.getActivity().getApplicationContext());
//        SerOrderPayActivity serOrderPayActivity=new SerOrderPayActivity();
//        serOrderPayActivity.registCallBack(SerOrderFragment.this);
    }


    @Override
    public void doBases() {

    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        switch (mCurIndex){
            case FIRST_FRAGMENT:
                reqServerMenu(mUserId,FIRST_FRAGMENT+1);
                break;
            case SECOND_FRAGMENT:
                reqServerMenu(mUserId,0);
                break;
        }

    }

    @Override
    public void showProgress() {
        try {
            showProgress(SerOrderFragment.this.getActivity());
        } catch (Exception e) {

        }
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception e) {

        }

    }

    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }

    @Override
    public int getLayoutView() {
        return R.layout.llh_fragment_listview;
    }


    @Override
    public void callBack() {

    }

    @Override
    public void refreshData() {

    }

    @Override
    public void deleteData(int position) {
      if (adapter!=null){
          serOrderInfoList.remove(position);
          adapter.notifyDataSetChanged();
      }

    }

    @Override
    public void updateData(int position) {

    }

    @Override
    public void deleteData(SerOrderInfo holderOnclickBea) {
            if (holderOnclickBea!=null){
                reqDeleteOrder(holderOnclickBea);
            }
    }

    @Override
    public void updateData(SerOrderInfo holderOnclickBea) {
        if (holderOnclickBea!=null){
//            Intent intent=new Intent(getActivity().getApplicationContext(),SerOrderPayActivity.class);
//            Bundle bundle=new Bundle();
//            bundle.putSerializable("serOrderInfo",holderOnclickBea);
//            intent.putExtras(bundle);
//            startActivity(intent);
        }
    }

    @Override
    public void reqData(SerOrderInfo holderOnclickBea) {

    }

    @Override
    public void insertData(SerOrderInfo holderOnclickBea) {

    }

    private void reqDeleteOrder(SerOrderInfo holderOnclickBea) {
        try {
            LRequest lRequest = new LRequest();
            lRequest.addParam("orderId",holderOnclickBea.getOrderId());
            lRequest.addParam("realId",holderOnclickBea.getOrderPersionId());
            lRequest.addParam("realName",holderOnclickBea.getOrderPersionName());
            lRequest.setUri(ServerPort.DELETE_SERVER_ORDER);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    closeProgress();
                    T.showAnimErrorToast(SerOrderFragment.this.getActivity(),   "请求超时！");
                }
                @Override
                public void onNext(String responseBean, String code) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    List<SerOrderInfo> serOrderInfoList=new ArrayList<SerOrderInfo>();
    private void reqServerMenu(String mUserId,int type) {
        try {
            LRequest lRequest = new LRequest();
            SerOrderInfo serOrderInfo=new SerOrderInfo();
            serOrderInfo.setCustomerId(mUserId);
            serOrderInfo.setPayStatus(type);
            String serOrder=new Gson().toJson(serOrderInfo);
            lRequest.addParam("serOrderInfoStr", URLEncoder.encode(serOrder,"utf-8"));
            lRequest.setUri(ServerPort.GET_SERVER_ORDER);
            lRequest.setIp(UrlsTools.SERVER_REQ_URL);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    try {
                        closeProgressa();
                        T.showAnimErrorToast(SerOrderFragment.this.getActivity(),   "请求超时！");
                    }catch (Exception e){
                    }
                }
                @Override
                public void onNext(String responseBean, String code) {
                    closeProgressa();
                    switch (mCurIndex){
                        case FIRST_FRAGMENT:
                            setData(responseBean);
                            break;
                        case SECOND_FRAGMENT:
                            setData(responseBean);
                            break;
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    SerOrderInfoHolder adapter=null;
    public void setData(String responseBean) {
        mHasLoadedOnce = true;
        serOrderInfoList.clear();
        if (responseBean != null) {
            serOrderInfoList=new Gson().fromJson(responseBean,new TypeToken<List<SerOrderInfo>>() {}.getType());
            if (serOrderInfoList!=null){
                if (SerOrderFragment.this.getActivity()!=null){
                    adapter=new SerOrderInfoHolder(SerOrderFragment.this.getActivity(),serOrderInfoList);
                    fragmentListview.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    adapter.registCallBack(SerOrderFragment.this);
                }
            }
        }
    }
public  void closeProgressa(){
    try{
        closeProgress();
    }catch (Exception E){

    }
}

}
